//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    imgUrls: [],
    recommendedList: [],
    dataList: [],
    currentData: 0,    
  },
  onLoad: function () {      
    wx.showLoading({
      title: '加载中'
    })   
    //获取幻灯片
    wx.request({
      url: 'https://sng.tsletu.com/api/home/slides/1',
      header: {
        'XX-Device-Type': 'wxapp',
        'XX-Token': app.globalData.token        
      },
      success: res => {        
        this.setData({
          imgUrls: res.data.data[0].items
        })
      }
    })

    if(this.data.currentData==0){
      this.getNewsCourse();
    } else if (this.data.currentData == 1){
      this.getRecommended();
    }
    
    
    wx.hideLoading()
    
  },
  getNewsCourse: function(e){    
    //获取最新课程
    wx.request({
      url: 'https://sng.tsletu.com/api/wxapp/course/newList',
      header: {
        'XX-Device-Type': 'wxapp',
        'XX-Token': app.globalData.token
      },
      success: res => {
        this.setData({
          dataList: res.data.data
        })
      }
    })
  },
  getRecommended: function(e){    
    //获取热门课程
    wx.request({
      url: 'https://sng.tsletu.com/api/wxapp/course/recommendedList',
      header: {
        'XX-Device-Type': 'wxapp',
        'XX-Token': app.globalData.token
      },
      success: res => {
        this.setData({
          dataList: res.data.data
        })
      }
    })
  },  
  //点击切换，滑块index赋值
  checkCurrent: function (e) {
    wx.showLoading({
      title: '加载中',
    })
    const that = this;
    if (that.data.currentData === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentData: e.target.dataset.current
      })

      if (e.target.dataset.current == 0) {
        this.getNewsCourse();
      } else if (e.target.dataset.current == 1) {
        this.getRecommended();
      }
    }

    
    wx.hideLoading()
    
  },
  toAllCourse: function(e){
    wx.navigateTo({
      url: '/pages/course/index'
    })
  },
  toDetail: function(e){    
    wx.navigateTo({      
      url: '/pages/detail/index?id=' + e.currentTarget.id
    })
  },  
  onPullDownRefresh: function(){    
    this.onLoad();
    wx.stopPullDownRefresh()
    wx.hideLoading();    
  }
})
